﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace UnitTests
{
	public partial class MainPage : UserControl
	{
		private TestDispatcher dispatcher;
		private int lastKnownMessageLength = 0;
		private int total = TestRegistry.TotalTests;
		private ThreadCommunicator communicator;

		public MainPage()
		{
			this.InitializeComponent();

			this.communicator = new ThreadCommunicator();
			
			this.dispatcher = new TestDispatcher(communicator);
			this.dispatcher.Completed += this.dispatcher_Completed;
			DispatcherTimer timer = new DispatcherTimer()
			{
				Interval = new TimeSpan(0, 0, 0, 0, 16)
			};

			timer.Tick += this.DoUpdate;
			timer.Start();

			this.dispatcher.Start();
		}

		private void dispatcher_Completed(object sender, EventArgs e)
		{
			this.text_list.Print("DONE!");
		}

		private void DisplayNewMessages()
		{
			TextMessage[] messages = this.communicator.GetMessagesAfter(this.lastKnownMessageLength);
			this.lastKnownMessageLength += messages.Length;
			foreach (TextMessage message in messages)
			{
				string text = message.Text;
				if (message.ShowNumber > 0)
				{
					text = "[" + message.ShowNumber.ToString() + "/" + this.total.ToString() + "] " + text;
				}

				if (message.IsPass)
				{
					this.text_list.Print(text);
				}
				else
				{
					this.text_list.PrintFail(text);
				}
			}
		}

		private void DoUpdate(object sender, EventArgs e)
		{
			this.dispatcher.Refresh();
			this.DisplayNewMessages();
		}
	}
}
